
const config = require('../../config/config.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputShowed: false,
    hotSearchs: ['毛血旺', '鱼香肉丝', '川菜', '微辣'],
    searchText: '',
    historySearchs: [],
    foods: [],
    startLoading: false,
    currentPage: 1,
    bottomLoading: false,
    alreadyBottom: false,

    orderPanelShow: false,
    orderStyles: config.foodOrderStyles,
    currentOrderStyleIndex: 0,
    orderRule: config.orderRuleMap.get(config.foodOrderStyles[0])

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSearchHistory()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // console.log("到底了")
    if (this.data.bottomLoading || this.data.alreadyBottom) {
      return
    }
    this.setData({
      bottomLoading: true
    })
    this.refreshSearchFoods(this.data.currentPage + 1).then(res => {
      if (res.length > 0) {
        this.setData({
          foods: this.data.foods.concat(res),
          bottomLoading: false,
          currentPage: this.data.currentPage + 1
        })
      } else {
        this.setData({
          bottomLoading: false,
          alreadyBottom: true
        })
      }
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  searchFocus: function () {

  },

  searchBlur: function () {
    // this.setData({
    //   inputShowed: false
    // })
  },

  searchInput: function (e) {
    let text = e.detail.value
    this.setData({
      searchText: text
    })
  },

  clickLabel: function (event) {
    let text = event.currentTarget.dataset.text
    this.setData({
      searchText: text
    })
  },

  clickMask: function () {
    this.setData({
      inputShowed: false,
      orderPanelShow: false
    })
  },

  showInput: function () {
    this.setData({
      inputShowed: true,
      orderPanelShow: false,
    });
  },

  clickSearch: function () {
    this.addSearchHistoty()
    this.setData({
      inputShowed: false,
    })
    if (this.data.searchText == '' || this.data.searchText.length == 0) {
      return
    }
    this.setData({
      startLoading: true,
      currentPage: 1,
      bottomLoading: false,
      alreadyBottom: false
    })
    this.refreshSearchFoods(this.data.currentPage).then(res => {
      // console.log(res)
      this.setData({
        foods: res,
        startLoading: false
      })
    })
  },

  addSearchHistoty: function () {
    if (this.data.searchText == '' || this.data.searchText.length == 0) {
      return
    }
    let that = this
    let text = this.data.searchText
    let hisData = wx.getStorageSync('searchHistoryKey')
    if (hisData) {
      if (hisData.indexOf(text) < 0) {
        hisData.unshift(text)
      }
      wx.setStorage({
        key: "searchHistoryKey",
        data: hisData,
        success: function () {
          that.getSearchHistory()
        }
      })
    } else {
      hisData = []
      hisData.push(text)
      wx.setStorage({
        key: 'searchHistoryKey',
        data: hisData,
        success: function () {
          that.getSearchHistory()
        }
      })
    }
  },

  getSearchHistory: function () {
    let hisData = wx.getStorageSync('searchHistoryKey')
    if (hisData) {
      this.setData({
        historySearchs: hisData
      })
    }
  },


  clearSearchHistory: function () {
    let that = this
    wx.removeStorage({
      key: 'searchHistoryKey',
      success: function(res) {
        that.setData({
          historySearchs: []
        })
      },
    })
  },


  refreshSearchFoods: function (requestPage) {
    // console.log(requestPage)
    let that = this
    return new Promise(resolve => {
      wx.getLocation({
        success: function(res) {
          wx.request({
            url: `${config.requestBaseUrl}/Dishes/getFoods`,
            method: 'POST',
            data: {
              latitude: res.latitude,
              longitude: res.longitude,
              page: requestPage,
              openid: wx.getStorageSync('openid'),
              key_word: that.data.searchText,
              food_style: '',
              order_rule: that.data.orderRule
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              // console.log(res.data)
              // return
              let data = res.data
              for (let i = 0, len = data.length; i < len; i++) {
                let distance = data[i]['distance']
                data[i]['distance'] = distance < 1 ? Math.round(distance * 1000) + 'm' : Math.round(distance * 10) / 10 + 'km'
              }
              // console.log(data)
              resolve(data)
            }
          })
        },
      })
    })
  },


  clickCollect: function (event) {
    // console.log(event)
    let that = this
    let foodId = event.currentTarget.dataset.id
    let index = event.currentTarget.dataset.index
    wx.request({
      url: `${config.requestBaseUrl}/Collect/CollectFood`,
      method: 'POST',
      data: {
        food_id: foodId,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code != 0) {
          let foods = that.data.foods
          foods[index].is_collect = res.data.code === 1 ? 1 : 0
          foods[index].collect_num = res.data.code === 1 ? parseInt(foods[index].collect_num) + 1 : parseInt(foods[index].collect_num) - 1
          that.setData({
            foods: foods
          })
        }
      }
    })
  },

  clickOrderRuleBtn: function() {
    this.setData({
      orderPanelShow: !this.data.orderPanelShow,
      inputShowed: false
    })
  },

  selectOrderRule(event) {
    let index = event.currentTarget.dataset.index
    this.setData({
      orderPanelShow: false,
    })
    if (index == this.data.currentOrderStyleIndex || this.data.searchText == '') {
      return
    }
    this.setData({
      currentPage: 1,
      currentOrderStyleIndex: index,
      orderRule: config.orderRuleMap.get(this.data.orderStyles[index]),
      startLoading: true,
      alreadyBottom: false,
      bottomLoading: false
    })
    this.refreshSearchFoods(this.data.currentPage).then(res => {
      // console.log(res)
      this.setData({
        foods: res,
        startLoading: false
      })
    })
  }


  

})